package devcontainer

import (
	"context"

	"code.gitea.io/gitea/models/db"
	"code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/models/user"
)

func CreateDevcontainerAPIService(ctx context.Context, repo *repo.Repository, doer *user.User, publicKeyList []string, isWebTerminal bool) error {
	var userSSHPublicKeyList []string
	err := db.GetEngine(ctx).
		Table("public_key").
		Select("content").
		Where("owner_id = ?", doer.ID).
		Find(&userSSHPublicKeyList)
	if err != nil {
		return err
	}
	allPublicKeyList := append(userSSHPublicKeyList, publicKeyList...)
	return CreateDevContainer(ctx, repo, doer, allPublicKeyList, isWebTerminal)
}

// OpenDevcontainerAPIService  API 专用获取 DevContainer Service
func OpenDevcontainerAPIService(ctx context.Context, userID, repoID int64) (*DevcontainerVO, error) {
	var devcontainerDetails DevcontainerVO
	dbEngine := db.GetEngine(ctx)
	// 2. 查询数据库
	_, err := dbEngine.
		Table("devcontainer").
		Select(""+
			"devcontainer.id                                   AS devcontainer_id,"+
			"devcontainer.name                                 AS devcontainer_name,"+
			"devcontainer.devcontainer_host                    AS devcontainer_host,"+
			"devcontainer.devcontainer_status                    AS devcontainer_status,"+
			"devcontainer.devcontainer_username                AS devcontainer_username,"+
			"devcontainer.devcontainer_work_dir                AS devcontainer_work_dir,"+
			"devcontainer.repo_id                              AS repo_id,"+
			"devcontainer.user_id                              AS user_id,"+
			"repository.name                                           AS repo_name,"+
			"repository.owner_name                                     AS repo_owner_name,"+
			"repository.description                                    AS repo_description,"+
			"CONCAT('/', repository.owner_name, '/', repository.name)  AS repo_link").
		Join("INNER", "repository", "devcontainer.repo_id = repository.id").
		Where("devcontainer.user_id = ? AND devcontainer.repo_id = ?", userID, repoID).
		Get(&devcontainerDetails)
	if err != nil {
		return &devcontainerDetails, err
	}
	// 2. 获取实时port
	devcontainerDetails.DevContainerPort, err = GetMappedPort(ctx, devcontainerDetails.DevContainerName, "22")
	if err != nil {
		return &devcontainerDetails, err
	}
	return &devcontainerDetails, nil
}
